
package tfoundation.world;

import java.awt.Point;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import tfoundation.Body;

public class World
{
	private final List<Body> bodies;
	private final List<SelectionListener> selectionListeners;

	public final Body hero;
	// private final Clavier clavier;

	private final AutoCont autoCont;

	private Body testBody = null;
	private Body selection = null;
	private long timecode = 0;

	public World()
	{
		this.bodies = new ArrayList<Body>();
		this.selectionListeners = new ArrayList<SelectionListener>();

		// this.clavier = new Clavier();
		this.hero = new Body();

		this.autoCont = new AutoCont();

		this.autoCont.setListening(false);
		this.hero.setLocation(100, 50);

		this.bodies.add(this.hero);

		// Test
		this.testBody = new Body();
		this.testBody.broadcastName = "station alpha";
		this.testBody.setLocation(150, 50);
		this.testBody.anchored = true;
		this.testBody.setSizeClass(4);
		this.bodies.add(this.testBody);

		this.testBody = new Body();
		this.testBody.broadcastName = "Survey ship";
		this.testBody.setSizeClass(2);
		this.testBody.setLocation(400, 400);
		this.bodies.add(this.testBody);
	}

	public List<Body> getBodies()
	{
		return this.bodies;
	}

	public void update()
	{

		ListIterator<Body> ite = null;

		Body tempBody = null;

		this.hero.correctOrientation();

		// this.hero.translate((int) this.hero.spdX, (int) this.hero.spdY);

		this.timecode++;

		ite = this.bodies.listIterator();
		while (ite.hasNext())
		{
			tempBody = ite.next();
			tempBody.decideNextAction();
		}
	}

	public long getTimecode()
	{
		return this.timecode;
	}

	public Body getHero()
	{
		return this.hero;
	}

	public void sendSelectionRequest(Point p)
	{
		Body b = this.searchForSelection(p);

		if (b != null)
		{
			this.setSelectedBody(b);
		}
	}

	public void addSelectionListener(SelectionListener sl)
	{
		this.selectionListeners.add(sl);
	}

	public Body getSelection()
	{
		return this.selection;
	}

	public AutoController getAutoController()
	{
		return this.autoCont;
	}

	private void setSelectedBody(Body selection)
	{
		ListIterator<SelectionListener> ite = null;
		SelectionListener temp = null;

		ite = this.selectionListeners.listIterator();

		this.selection = selection;

		while (ite.hasNext())
		{
			temp = ite.next();

			temp.selectionChanged(selection);
		}
	}

	private Body searchForSelection(Point p)
	{
		return null;
	}

	private class AutoCont extends AutoController
	{
		private final Point currentFocus;

		private AutoCont()
		{
			this.currentFocus = new Point();
		}

		@Override
		public Point getCurrentFocus()
		{
			return new Point(this.currentFocus);
		}

		@Override
		public void setCurrentSelection(Point p)
		{
			this.currentFocus.setLocation(p);
		}
	}
}
